<?php

cload("database.dbquery");
cload("object");
/**
 * Description of ddrow
 *
 * @author Di_Moon
 */
class ddrow {
    protected $_dbh;                    // связь с бд
    protected $_row_for;                // идент набора ДД (фильма/раздачи)
    protected $_row_id;                 // идентификатор "строки" данных
    
    protected $_fields;                 // Поля записи
    protected $_data;                   // Данные записи
    protected $_predata;                // Данные при инициализации
    
    function __construct($dbh, $row_for, $row_id="unknown:0") {
        $this->_dbh = $dbh;
        $this->_row_for = (int)$row_for;
        $this->_row_id = $row_id;
        $this->_fields = array();
        $this->_data = new object();
        $this->_predata = new object();
        
        $sql = new dbquery($this->_dbh);
        $sql->select()->from("dd_fields")->where("fld_for=".$this->_row_for);
        $sth = $this->_dbh->query($sql);
        while($fa = $this->_dbh->raw_fetch_array($sth)) {
            $this->_fields[$fa->id] = $fa;
            $this->_data->set($fa->fld_name, null);
        }
        
        $this->load();
        
        foreach($this->_data->getElements() as $key=>$value) {
            $this->_predata->set($key, $value);
        }
    }
    
    // Загрузка данных
    function load() {
        $sql = new dbquery($this->_dbh);
        $sql->select()->from("dd_data")->where("row_id='".$this->_row_id."'");
        $sth = $this->_dbh->query($sql);
        while($fa=$this->_dbh->raw_fetch_array($sth)) {
            $this->_data->set($this->_fields[$fa->fld]->fld_name, $fa->data);
        }
    }
    
    // Добавление поля
    function addField($fldname, $fldtitle, $fldtype) {
//        _print_r($this->_fields);
        foreach($this->_fields as $_fld) {
            // Если поле с указанным именем есть, вернём false
            if($_fld->fld_name == $fldname) return false;
        }
        
        $sql = new dbquery($this->_dbh);
        $sql->insert()->into("dd_fields")
                ->field("fld_name", addslashes($fldname))
                ->field("fld_title", addslashes($fldtitle))
                ->field("fld_type", $fldtype)
                ->field("fld_for", $this->_row_for);
        $this->_dbh->query($sql);
        $sql = new dbquery($this->_dbh);
        $sql->select()->from("dd_fields")->where("fld_for=".$this->_row_for." and fld_name='".addslashes($fldname)."'");
        $sth = $this->_dbh->query($sql);
        $_fa = $this->_dbh->raw_fetch_array($sth);

//        _print_r($_fa);
        $this->_fields[$_fa->id] = $_fa;
        $this->_data->set($_fa->fld_name, null);
        $this->_predata->set($_fa->fld_name, null);
        
//        _print_r($this->_fields);

        return true;
    }

    // Получение данных
    function getData() { return $this->_data->getElements(); }
    
    function getDataHTML() {
        $arr = array();
        
        foreach($this->getData() as $key=>$value) {
            $arr[$key] = htmlspecialchars($value);
        }
        
        return $arr;
    }
    
    function getDefaultData($field) {
        $_id = "0";
        foreach($this->_fields as $_fld) {
            if($_fld->fld_name == $field) $_id=$_fld->id;
        }
        if($_id==0) return null;
        $sql = new dbquery($this->_dbh);
        $sql->select()->from("dd_default")->where("fld=".$_id);
        $sth=$this->_dbh->query($sql);
        if($fa=$this->_dbh->raw_fetch_array($sth)) {
            return $fa->value;
        }
        return null;
    }
    
    function setDefaultData($field, $value) {
        $sql = new dbquery($this->_dbh);
        $id = $this->getFieldId($field);
        if($id==null) return;
        
        if($this->getDefaultData($field)==null) {
            $sql->insert()->into("dd_default")
                    ->field("fld", $id)
                    ->field("value", addslashes($value));
        } else {
            $sql->update("dd_default")
                    ->field("value", addslashes($value))
                    ->where("fld=".$id);
        }
        $this->_dbh->query($sql);
    }
    
    function getFieldId($field) {
        foreach($this->getFields() as $id=>$fld) {
            if($fld->fld_name==$field) return $id;
        }
        return null;
    }
    
    function getFields() { return $this->_fields; }

    function set($field, $value) {
        // найдём, есть ли указаное поле в записи
        $fldPresent = false;
        foreach($this->_fields as $_fld) {
            if($_fld->fld_name == $field) $fldPresent = true;
        }
        if(!$fldPresent) return false;
        $this->_data->set($field, $value);
    }
    
    // сохранение строки в БД
    function save() {
        foreach($this->_fields as $_fld) {
            $_field = $_fld;
            $_fld_name = $_fld->fld_name;
            $_fld_id = $_fld->id;
            
            if($this->_predata->get($_fld_name)==null) {
//                echo "insert<br>";
                $this->_insert($_fld_id, $this->_data->get($_fld_name));
            } else {
//                echo "update<br>";
                $this->_update($_fld_id, $this->_data->get($_fld_name));
            }
        }
    }
    
    // Обновление записи
    //   $field - id поля
    //   $data - данные поля
    protected function _update($field, $data) {
        if($data==null) return;
        $sql = new dbquery($this->_dbh);
        $sql->update("dd_data")->field("data", addslashes($data))->where("fld=$field and row_id='".$this->_row_id."'");
        $this->_dbh->query($sql);
    }
    
    protected function _insert($field, $data) {
        if($data==null) return;
        $sql = new dbquery($this->_dbh);
        $sql->insert()->into("dd_data")
                ->field("fld", $field)
                ->field("row_id", $this->_row_id)
                ->field("data", addslashes($data));
        $this->_dbh->query($sql);
    }
    
    function updateFieldTitle($field, $newTitle) {
        foreach($this->_fields as $_fld) {
            if($_fld->fld_name == $field) {
                $id = $_fld->id;
                $sql = new dbquery($this->_dbh);
                $sql->update("dd_fields")->field("fld_title", addslashes($newTitle))->where("id=$id");
                $this->_dbh->query($sql);
                $this->_fields[$_fld->id]->fld_title = $newTitle;
                return true;
            }
        }
        return false;
    }
}
?>
